﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Chowpoo.Util;
using CourseSystem.Common.Helpers;
using CourseSystem.Core.BLL;
using CourseSystem.Core.Entities;
using CourseSystem.Core.Enum;
using Webdiyer.WebControls.Mvc;

namespace CourseSystem.Web.Controllers
{
    public class AdminController : Controller
    {
        private void ClearCache()
        {
            //禁止页面被缓存
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.Today.AddYears(-2));
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult CourseManage()
        {
            return View();
        }

        public ActionResult College()
        {
            return View();
        }

        public ActionResult CollegeListUc(int? pid)
        {
            ClearCache();
            var list = CollegeBLL.GetList().OrderByDescending(o => o.Id);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView("CollegeListUc", model);
        }

        public ActionResult CollegeEditUc(int? id)
        {
            if (id.HasValue)
            {
                var info = CollegeBLL.Get(id.Value);
                if (info == null)
                    return View("NotFound");
                return PartialView("CollegeEditUc", info);
            }
            return PartialView(new CollegeInfo());
        }

        [HttpPost]
        public ActionResult CollegeEditUc(CollegeInfo info)
        {
            if (!ModelState.IsValid)
                return PartialView();
            if (info.Id != 0)
            {
                if (CollegeBLL.IsExist(o => o.Id != info.Id && o.Name == info.Name))
                {
                    ModelState.AddModelError("Name", "已存在相同名字的学院.");
                    return PartialView();
                }
                var oldInfo = CollegeBLL.Get(info.Id);
                if (oldInfo == null)
                    return View("NotFound");
                oldInfo.Name = info.Name;
                if (CollegeBLL.Edit(oldInfo))
                {
                    ViewData["msg"] = "编辑成功.";
                    return PartialView();
                }
                ViewData["msg"] = "未知错误.";
                return PartialView();
            }
            if (CollegeBLL.IsExist(o => o.Name == info.Name))
            {
                ModelState.AddModelError("Name", "已存在相同名字的学院.");
                return PartialView();
            }
            if (CollegeBLL.Add(info))
            {
                ViewData["msg"] = "编辑成功.";
                return PartialView();
            }
            ViewData["msg"] = "未知错误.";
            return PartialView();
        }

        public ActionResult SubjectList(int id)
        {
            var info = CollegeBLL.Get(id);
            if (info == null)
                return View("NotFound");
            return View(info);
        }

        public ActionResult SubjectListUc(int id, int? pid)
        {
            ClearCache();
            var list = SubjectBLL.GetList(id).OrderByDescending(o => o.Id);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView("SubjectListUc", model);
        }

        public ActionResult StudentDel(string ids)
        {
            if (string.IsNullOrEmpty(ids))
            {
                TempData["AlertMsg"] = "未知参数.";
                return RedirectToAction("Student");
            }
            //ids = ids.TrimEnd(',');
            var idArray = ids.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (StudentBLL.Del(idArray))
            {
                TempData["AlertMsg"] = "删除成功.";
                return RedirectToAction("Student");
            }
            TempData["AlertMsg"] = "未知错误.";
            return RedirectToAction("Student");
        }

        public ActionResult StudentReviewUc(string ids)
        {
            if (string.IsNullOrEmpty(ids))
            {
                TempData["AlertMsg"] = "未知参数.";
                return RedirectToAction("Student");
            }
            ViewData["ids"] = ids;
            return PartialView();
        }

        public ActionResult StudentReview(string ids, int type)
        {
            if (string.IsNullOrEmpty(ids))
            {
                TempData["AlertMsg"] = "未知参数.";
                return RedirectToAction("Student");
            }
            ids = ids.TrimEnd(',');
            //只能设置通过或未通过
            if (type != 1 && type != 2)
            {
                TempData["AlertMsg"] = "未知参数.";
                return RedirectToAction("Student");
            }
            if (StudentBLL.Review(ids, type))
            {
                TempData["AlertMsg"] = "设置成功.";
                return RedirectToAction("Student");
            }
            TempData["AlertMsg"] = "未知错误.";
            return RedirectToAction("Student");
        }

        public ActionResult SubjectEditUc(int? id, int cid)
        {
            if (id.HasValue)
            {
                var info = SubjectBLL.Get(id.Value);
                if (info == null)
                    return View("NotFound");
                return PartialView("SubjectEditUc", info);
            }
            return PartialView(new SubjectInfo { CollegeId = cid });
        }

        [HttpPost]
        public ActionResult SubjectEditUc(SubjectInfo info, int cid)
        {
            if (!ModelState.IsValid)
                return PartialView();
            if (info.Id != 0)
            {
                var oldInfo = SubjectBLL.Get(info.Id);

                if (SubjectBLL.IsExist(o => o.CollegeId == oldInfo.CollegeId && o.Id != info.Id && o.Name == info.Name))
                {
                    ModelState.AddModelError("Name", "已存在相同名字的专业.");
                    return PartialView();
                }

                if (oldInfo == null)
                    return View("NotFound");
                oldInfo.Name = info.Name;
                if (SubjectBLL.Edit(oldInfo))
                {
                    ViewData["msg"] = "编辑成功.";
                    return PartialView();
                }
                ViewData["msg"] = "未知错误.";
                return PartialView();
            }
            if (SubjectBLL.IsExist(o => o.CollegeId == cid && o.Name == info.Name))
            {
                ModelState.AddModelError("Name", "已存在相同名字的专业.");
                return PartialView();
            }
            info.CollegeId = cid;
            if (SubjectBLL.Add(info))
            {
                ViewData["msg"] = "编辑成功.";
                return PartialView();
            }
            ViewData["msg"] = "未知错误.";
            return PartialView();
        }

        public ActionResult Student()
        {
            return View();
        }

        public ActionResult StudentListUc(int? pid, int? collegeIdSearch, int? subjectIdSearch, int? classIdSearch, string uidSearch, string nameSearch)
        {
            ClearCache();
            var list = StudentBLL.GetList(collegeIdSearch.CheckInt(0), subjectIdSearch.CheckInt(0), classIdSearch.CheckInt(0), uidSearch, nameSearch).OrderByDescending(o => o.Id);
            var model = list.ToPagedList(pid ?? 1, CommonHelper.PageSize);
            return PartialView(model);
        }

        public ActionResult StudentEditUc(int? id)
        {
            if (id.HasValue)
            {
                var info = StudentBLL.Get(id.Value);
                if (info == null)
                    return View("NotFound");
                info.CollegeIdFake = info.SubjectInfo.CollegeId;
                return PartialView(info);
            }
            return PartialView(new StudentInfo());
        }

        [HttpPost]
        public ActionResult StudentEditUc(StudentInfo info)
        {
            StudentInfo oldInfo = null;
            if (info.Id != 0)
            {
                oldInfo = StudentBLL.Get(info.Id);
                if (oldInfo == null)
                    return View("NotFound");
                oldInfo.CollegeIdFake = info.CollegeIdFake;
                ViewData.Model = oldInfo;
            }
            else
                ViewData.Model = info;
            if (!ModelState.IsValid)
                return PartialView();
            if (info.Id != 0)
            {
                if (oldInfo == null)
                    return View("NotFound");
                if (StudentBLL.IsExist(info.Uid, info.Id))
                {
                    ModelState.AddModelError("Uid", "已存在相同学号.");
                    return PartialView();
                }
                oldInfo.Uid = info.Uid;
                oldInfo.StuName = info.StuName;
                oldInfo.Class = info.Class;
                oldInfo.SubjectId = info.SubjectId;
                if (!string.IsNullOrEmpty(info.PassWord))
                {
                    if (info.PassWord.Length < 6 || info.PassWord.Length > 20)
                    {
                        ModelState.AddModelError("PassWord", "密码长度必须为6到20位.");
                        return PartialView();
                    }
                    oldInfo.PassWord = Security.Pass2Md5(info.PassWord);
                }
                if (StudentBLL.Edit(oldInfo))
                {
                    ViewData["msg"] = "编辑成功.";
                    return PartialView(oldInfo);
                }
                ViewData["msg"] = "未知错误.";
                return PartialView();
            }
            if (string.IsNullOrEmpty(info.PassWord) || info.PassWord.Length < 6 || info.PassWord.Length > 20)
            {
                ModelState.AddModelError("PassWord", "密码长度必须为6到20位.");
                return PartialView();
            }
            if (StudentBLL.IsExist(info.Uid))
            {
                ModelState.AddModelError("Uid", "已存在相同学号.");
                return PartialView();
            }
            info.LastIp = "";
            info.LastUrl = "";
            info.LearnTimes = 0;
            info.RegDate = DateTime.Now;
            info.RegType = (byte)RegReviewEnum.HaveNotReview;
            info.Score = 0;
            info.PassWord = Security.Pass2Md5(info.PassWord);
            if (StudentBLL.Add(info))
                ViewData["msg"] = "添加成功.";
            else
                ViewData["msg"] = "未知错误.";
            return PartialView();
        }

        public ActionResult AdminDefault()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ImportStudent()
        {
            HttpPostedFileBase importFile = Request.Files["fileField"];
            if (importFile == null || importFile.ContentLength <= 0)
            {
                TempData["AlertMsg"] = "请选择文件！";
                return RedirectToAction("Student");
            }
            if (CommonUtils.GetFileExtName(importFile.FileName) != ".csv")
            {
                TempData["AlertMsg"] = "导入失败！请用模板导入！导入文件仅限CSV格式！";
                return RedirectToAction("Student");
            }
            try
            {
                var error = "";
                using (var sr = new StreamReader(importFile.InputStream, Encoding.GetEncoding("GB2312")))
                {
                    string line = sr.ReadLine();
                    int i = 0;
                    var importList = new List<StudentInfo>(20);
                    DateTime now = DateTime.Now;

                    while (!string.IsNullOrEmpty(line))
                    {
                        try
                        {
                            line = sr.ReadLine();
                            if (string.IsNullOrEmpty(line))
                                break;
                            ++i;
                            {
                                string[] lineSp = line.Split(',');
                                var name = lineSp[1];
                                if (string.IsNullOrEmpty(name))
                                {
                                    error += (i + ",");
                                    continue;
                                }
                                var num = lineSp[0].CheckInt(0);
                                if (num == 0 || StudentBLL.IsExist(num.ToString()))
                                {
                                    error += (i + ",");
                                    continue;
                                }
                                var subInfo = SubjectBLL.Get(lineSp[2], lineSp[3]);
                                if (subInfo == null)
                                {
                                    error += (i + ",");
                                    continue;
                                }
                                var classInfo = ClassBLL.Get(lineSp[5].CheckInt(0));
                                if (classInfo == null)
                                {
                                    error += (i + ",");
                                    continue;
                                }
                                var yearInfo = GradeYearBLL.Get(lineSp[4].CheckInt(0));
                                if (yearInfo == null)
                                {
                                    error += (i + ",");
                                    continue;
                                }
                                importList.Add(new StudentInfo
                                                   {
                                                       Class = classInfo.Id,
                                                       GradeYear = yearInfo.Id,
                                                       PassWord = Security.Pass2Md5(CommonHelper.StudentDefPassWord),
                                                       RegDate = now,
                                                       RegType = (byte)RegReviewEnum.Pass,
                                                       StuName = name,
                                                       Uid = num.ToString(),
                                                       SubjectId = subInfo.Id
                                                   });
                            }
                        }
                        catch (Exception ex)
                        {
                            error += (i + ",");
                        }
                    }

                    if (StudentBLL.Add(importList))
                    {
                        TempData["AlertMsg"] = "导入成功！";
                        if (!string.IsNullOrEmpty(error))
                        {
                            TempData["AlertMsg"] = "第" + error + "行导入失败,请检查数据!";
                        }
                    }
                    else
                        TempData["AlertMsg"] = "导入失败!未知错误!";
                    return RedirectToAction("Student");
                }
            }
            catch (Exception ex)
            {
                TempData["AlertMsg"] = "导入失败！请用模板导入！导入文件仅限CSV格式，内容不可带有逗号.";
                return RedirectToAction("Student");
            }

        }

        public ActionResult ExportStudent(int? collegeIdSearch, int? subjectIdSearch, int? classIdSearch, string uidSearch, string nameSearch)
        {
            ClearCache();
            var infoList = StudentBLL.GetList(collegeIdSearch.CheckInt(0), subjectIdSearch.CheckInt(0), classIdSearch.CheckInt(0), uidSearch, nameSearch).OrderByDescending(o => o.Id);
            var sb = new StringBuilder(1000);
            sb.AppendLine("序号,学号,姓名,学院,专业,年级,班级");
            int i = 1;
            foreach (var item in infoList)
            {
                sb.AppendLine((i++) + "," + item.Uid + "," +
                              item.StuName
                              + "," +
                              item.SubjectInfo.CollegeInfo.Name + "," + item.SubjectInfo.Name
                              + "," + item.GradeYearInfo.Year + "," + item.ClassInfo.Class);
            }
            string filename = string.Format("{1}_{0:yyyyMMdd_hhmmss}.csv", DateTime.Now, "学生");
            byte[] buffer = Encoding.Default.GetBytes(sb.ToString());
            var outPutStream = new MemoryStream(buffer) { Position = 0 };
            HttpContext.Response.ContentType = "text/csv; charset=gb2312";
            return File(outPutStream, "text/csv", filename);
        }
    }
}
